<!-- The exported code uses Tailwind CSS. Install Tailwind CSS in your dev environment to ensure all styles work. -->
<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 -->
    <Header />
    <!-- 左侧导航栏 -->
    <aside class="fixed left-0 top-16 bottom-0 w-64 bg-gray-800 text-white z-10 overflow-y-auto">
      <nav class="py-4">
        <div v-for="(menu, index) in mainMenus" :key="index" class="mb-1">
          <div class="flex items-center px-6 py-3 cursor-pointer hover:bg-gray-700"
            :class="{ 'bg-blue-700': menu.active }" @click="toggleMenu(index)">
            <i :class="menu.icon + ' mr-3 w-5 text-center'"></i>
            <span>{{ menu.name }}</span>
            <i class="fas fa-chevron-down ml-auto text-xs transition-transform duration-200"
              :class="{ 'transform rotate-180': menu.expanded }"></i>
          </div>
          <div v-if="menu.expanded" class="bg-gray-900">
            <div v-for="(submenu, subIndex) in menu.subMenus" :key="subIndex"
              class="flex items-center px-10 py-2 cursor-pointer hover:bg-gray-700"
              :class="{ 'text-blue-400': submenu.active }" @click="selectSubmenu(index, subIndex)">
              <a v-if="submenu.link" :href="submenu.link" data-readdy="true" class="text-sm w-full">{{ submenu.name
              }}</a>
              <span v-else class="text-sm">{{ submenu.name }}</span>
            </div>
          </div>
        </div>
      </nav>
    </aside>
    <!-- 主内容区域 -->
    <main class="pt-16 pl-64">
      <div class="container mx-auto p-6">
        <!-- 面包屑导航 -->
        <div class="flex items-center text-sm mb-4 text-gray-500">
          <span>首页</span>
          <i class="fas fa-chevron-right mx-2 text-xs"></i>
          <span>综合分析</span>
          <i class="fas fa-chevron-right mx-2 text-xs"></i>
          <a href="https://readdy.ai/home/2aadf73d-355f-4962-b7ac-b983b1785a7f/67f59d47-e926-4201-b310-2a1096559db9"
            data-readdy="true" class="text-blue-600">定期专题报告</a>
        </div>
        <!-- 筛选条件区域 -->
        <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
          <div class="flex flex-wrap items-center gap-4">
            <!-- 报告类型筛选 -->
            <div class="flex items-center">
              <span class="text-gray-600 mr-2">报告类型：</span>
              <div class="relative">
                <button @click="toggleReportTypeDropdown"
                  class="flex items-center justify-between w-48 px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg focus:outline-none !rounded-button whitespace-nowrap cursor-pointer">
                  <span class="text-gray-700">{{ currentReportTypeLabel }}</span>
                  <i class="fas fa-chevron-down text-gray-500 text-xs"></i>
                </button>
                <!-- 报告类型下拉菜单 -->
                <div v-if="showReportTypeDropdown"
                  class="absolute top-full left-0 mt-1 w-48 bg-white rounded-lg shadow-lg border border-gray-200 z-20 max-h-60 overflow-y-auto">
                  <div class="py-1">
                    <div v-for="option in reportTypeOptions" :key="option.value" @click="selectReportType(option.value)"
                      class="px-3 py-2 text-sm cursor-pointer hover:bg-gray-100 transition-colors" :class="{
                        'bg-blue-50 text-blue-600 font-medium':
                          reportType === option.value,
                        'text-gray-700': reportType !== option.value,
                      }">
                      {{ option.label }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- 时间范围筛选  -->
            <div class="flex items-center">
              <span class="text-gray-600 mr-2">时间范围：</span>
              <div class="flex items-center">
                <input type="date" v-model="tempStartDate" placeholder="开始日期"
                  class="w-32 px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none" />
                <span class="mx-2 text-gray-500">至</span>
                <input type="date" v-model="tempEndDate" placeholder="结束日期"
                  class="w-32 px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none" />
                <!-- 筛选按钮 -->
                <button
                  class="ml-2 px-4 py-2 bg-blue-600 text-white rounded-lg flex items-center !rounded-button whitespace-nowrap cursor-pointer hover:bg-blue-700 transition-colors"
                  @click="applyDateFilter">
                  <i class="fas fa-filter mr-2"></i> 筛选
                </button>
                <!-- 添加清除按钮 -->
                <button v-if="isDateFilterApplied"
                  class="ml-2 px-3 py-2 bg-gray-300 text-gray-700 rounded-lg flex items-center !rounded-button whitespace-nowrap cursor-pointer hover:bg-gray-400 transition-colors"
                  @click="clearDateFilter">
                  <i class="fas fa-times mr-1"></i> 清除
                </button>
              </div>
            </div>

            <!-- 搜索框 -->
            <div class="flex items-center">
              <div class="relative">
                <input type="text" v-model="searchKeyword" placeholder="搜索报告标题"
                  class="w-64 pl-10 pr-4 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none"
                  @input="handleSearch" />
                <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
              </div>
            </div>

            <!-- 新建报告按钮 -->
            <div class="ml-auto">
              <button
                class="px-4 py-2 bg-blue-600 text-white rounded-lg flex items-center !rounded-button whitespace-nowrap cursor-pointer hover:bg-blue-700 transition-colors"
                @click="showNewReportModal = true">
                <i class="fas fa-plus mr-2"></i> 新建报告
              </button>
            </div>
          </div>
        </div>
        <!-- 报告统计卡片 -->
        <div class="grid grid-cols-4 gap-4 mb-6">
          <!-- 总报告数量卡片 -->
          <div class="bg-white rounded-lg shadow-sm p-4 flex items-center">
            <div class="w-12 h-12 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 mr-4">
              <i class="fas fa-file-alt text-xl"></i>
            </div>
            <div>
              <div class="text-sm text-gray-500">总报告数量</div>
              <div class="text-2xl font-bold text-gray-900">128</div>
              <div class="text-xs text-green-600 flex items-center">
                <i class="fas fa-arrow-up mr-1"></i> 环比增长 12.5%
              </div>
            </div>
          </div>
          <!-- 本月新增卡片 -->
          <div class="bg-white rounded-lg shadow-sm p-4 flex items-center">
            <div class="w-12 h-12 rounded-full bg-green-100 flex items-center justify-center text-green-600 mr-4">
              <i class="fas fa-calendar-plus text-xl"></i>
            </div>
            <div>
              <div class="text-sm text-gray-500">本月新增</div>
              <div class="text-2xl font-bold text-gray-900">18</div>
              <div class="text-xs text-green-600 flex items-center">
                <i class="fas fa-arrow-up mr-1"></i> 环比增长 8.3%
              </div>
            </div>
          </div>
          <!-- 待阅报告卡片 -->
          <div class="bg-white rounded-lg shadow-sm p-4 flex items-center">
            <div class="w-12 h-12 rounded-full bg-yellow-100 flex items-center justify-center text-yellow-600 mr-4">
              <i class="fas fa-hourglass-half text-xl"></i>
            </div>
            <div>
              <div class="text-sm text-gray-500">待阅报告</div>
              <div class="text-2xl font-bold text-gray-900">24</div>
              <div class="text-xs text-red-600 flex items-center">
                <i class="fas fa-arrow-up mr-1"></i> 环比增长 15.2%
              </div>
            </div>
          </div>
          <!-- 下载次数卡片 -->
          <div class="bg-white rounded-lg shadow-sm p-4 flex items-center">
            <div class="w-12 h-12 rounded-full bg-purple-100 flex items-center justify-center text-purple-600 mr-4">
              <i class="fas fa-download text-xl"></i>
            </div>
            <div>
              <div class="text-sm text-gray-500">下载次数</div>
              <div class="text-2xl font-bold text-gray-900">356</div>
              <div class="text-xs text-green-600 flex items-center">
                <i class="fas fa-arrow-up mr-1"></i> 环比增长 5.8%
              </div>
            </div>
          </div>
        </div>
        <!-- 报告分类统计 -->
        <div class="grid grid-cols-3 gap-6 mb-6">
          <!-- 报告分类分布 -->
          <div class="bg-white rounded-lg shadow-sm p-4 col-span-1">
            <div class="flex justify-between items-center mb-4">
              <h2 class="font-bold text-lg text-gray-800">报告分类分布</h2>
              <div class="text-xs text-gray-500">
                <i class="fas fa-sync-alt mr-1"></i> 更新于 {{ currentTime }}
              </div>
            </div>
            <div id="reportCategoryChart" class="h-80" ref="reportCategoryChart"></div>
          </div>
          <!-- 报告阅读趋势 -->
          <div class="bg-white rounded-lg shadow-sm p-4 col-span-2">
            <div class="flex justify-between items-center mb-4">
              <h2 class="font-bold text-lg text-gray-800">报告阅读趋势</h2>
              <div class="flex space-x-2">
                <button class="px-3 py-1 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer" :class="currentPeriod === 'week'
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 text-gray-700'
                  " @click="changePeriod('week')">
                  周
                </button>
                <button class="px-3 py-1 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer" :class="currentPeriod === 'month'
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 text-gray-700'
                  " @click="changePeriod('month')">
                  月
                </button>
                <button class="px-3 py-1 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer" :class="currentPeriod === 'year'
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 text-gray-700'
                  " @click="changePeriod('year')">
                  年
                </button>
              </div>
            </div>
            <div id="reportReadingTrendChart" class="h-80" ref="reportReadingTrendChart"></div>
          </div>
        </div>
        <!-- 报告列表 -->
        <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
          <div class="flex justify-between items-center mb-4">
            <h2 class="font-bold text-lg text-gray-800">专题报告列表</h2>
            <div class="flex space-x-2">
              <!-- 排序方式下拉菜单 -->
              <div class="relative">
                <button @click="toggleSortDropdown"
                  class="flex items-center justify-between px-3 py-1 bg-gray-100 text-gray-700 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer">
                  <span>排序方式</span>
                  <i class="fas fa-sort ml-2 text-xs"></i>
                </button>
                <!-- 排序下拉菜单 -->
                <div v-if="showSortDropdown"
                  class="absolute top-full right-0 mt-1 w-48 bg-white rounded-lg shadow-lg border border-gray-200 z-20">
                  <div class="py-1">
                    <div v-for="option in sortOptions" :key="option.value" @click="selectSort(option.value)"
                      class="px-3 py-2 text-sm cursor-pointer hover:bg-gray-100 transition-colors" :class="{
                        'bg-blue-50 text-blue-600 font-medium':
                          getCurrentSortValue() === option.value,
                        'text-gray-700': getCurrentSortValue() !== option.value,
                      }">
                      {{ option.label }}
                    </div>
                  </div>
                </div>
              </div>

              <!-- 阅读状态下拉菜单 -->
              <div class="relative">
                <button @click="toggleReadStatusDropdown"
                  class="flex items-center justify-between px-3 py-1 bg-gray-100 text-gray-700 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer">
                  <span>阅读状态</span>
                  <i class="fas fa-filter ml-2 text-xs"></i>
                </button>
                <!-- 阅读状态下拉菜单 -->
                <div v-if="showReadStatusDropdown"
                  class="absolute top-full right-0 mt-1 w-32 bg-white rounded-lg shadow-lg border border-gray-200 z-20">
                  <div class="py-1">
                    <div v-for="option in readStatusOptions" :key="option.value" @click="selectReadStatus(option.value)"
                      class="px-3 py-2 text-sm cursor-pointer hover:bg-gray-100 transition-colors" :class="{
                        'bg-blue-50 text-blue-600 font-medium':
                          readStatus === option.value,
                        'text-gray-700': readStatus !== option.value,
                      }">
                      {{ option.label }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead>
                <tr>
                  <th class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider">
                    报告标题
                  </th>
                  <th class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider text-left">
                    报告类型
                  </th>
                  <th class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider text-left">
                    发布时间
                  </th>
                  <th class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider">
                    阅读状态
                  </th>
                  <th class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider text-left">
                    阅读量
                  </th>
                  <th class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider">
                    操作
                  </th>
                </tr>
              </thead>
              <tbody class="bg-white divide-y divide-gray-200">
                <tr v-for="(report, index) in filteredAndPagedReports" :key="index" class="hover:bg-gray-50">
                  <td class="px-4 py-3">
                    <div class="flex items-center">
                      <div class="w-8 h-8 rounded-full flex items-center justify-center mr-3" :class="report.iconBg">
                        <i :class="report.icon + ' ' + report.iconColor"></i>
                      </div>
                      <div>
                        <div class="text-sm font-medium text-gray-900 cursor-pointer hover:text-blue-600"
                          @click="viewReport(report)">
                          {{ report.title }}
                        </div>
                        <div class="text-xs text-gray-500">
                          {{ report.author }}
                        </div>
                      </div>
                    </div>
                  </td>
                  <td class="px-4 py-3">
                    <span class="px-2 py-1 text-xs rounded-full justify-center" :class="report.typeClass">{{ report.type
                    }}</span>
                  </td>
                  <td class="px-4 py-3">
                    <div class="text-sm text-gray-900 justify-center">
                      {{ report.publishTime }}
                    </div>
                  </td>
                  <td class="px-4 py-3">
                    <div class="flex items-center justify-center">
                      <div class="w-2 h-2 rounded-full mr-2" :class="report.isRead ? 'bg-green-500' : 'bg-red-500'">
                      </div>
                      <span class="text-sm" :class="report.isRead ? 'text-green-600' : 'text-red-600'
                        ">{{ report.isRead ? "已读" : "未读" }}</span>
                    </div>
                  </td>
                  <td class="px-4 py-3">
                    <div class="text-sm text-gray-900 justify-center">
                      {{ report.readCount }}
                    </div>
                  </td>
                  <td class="px-4 py-3 whitespace-nowrap text-sm font-medium">
                    <div class="flex space-x-2 justify-center">
                      <button class="text-blue-600 hover:text-blue-800 !rounded-button whitespace-nowrap cursor-pointer"
                        @click="viewReport(report)">
                        <i class="fas fa-eye mr-1"></i> 查看
                      </button>
                      <button
                        class="text-green-600 hover:text-green-800 !rounded-button whitespace-nowrap cursor-pointer"
                        @click="downloadReport(report)">
                        <i class="fas fa-download mr-1"></i> 下载
                      </button>

                      <!-- 新增删除按钮 -->
                      <button class="text-red-600 hover:text-red-800 !rounded-button whitespace-nowrap cursor-pointer"
                        @click="confirmDeleteReport(report)">
                        <i class="fas fa-trash-alt mr-1"></i> 删除
                      </button>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
            <div class="flex justify-end  items-center mt-4">
              <!-- 使用Pagination组件 -->
              <Pagination :current-page="currentPage" :page-size="pageSize" :total="filteredTotalReports"
                @page-change="handlePageChange" @page-size-change="handlePageSizeChange" />
            </div>
          </div>
        </div>
        <!-- 热门报告推荐 -->
        <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
          <div class="flex justify-between items-center mb-4">
            <h2 class="font-bold text-lg text-gray-800">热门报告推荐</h2>
            <a href="#" class="text-sm text-blue-600 cursor-pointer hover:text-blue-800 transition-colors duration-200"
              @click.prevent="viewAllHotReports">
            </a>
          </div>
          <div class="grid grid-cols-4 gap-4">
            <el-card v-for="(report, index) in hotReports" :key="index"
              class="cursor-pointer hover:shadow-lg transition-shadow duration-300" :body-style="{ padding: '16px' }"
              @click="showHotReportDetail(report)">
              <div class="h-40 mb-3 rounded-lg overflow-hidden">
                <img :src="report.coverImage" alt="报告封面" class="w-full h-full object-cover object-top" />
              </div>
              <div class="flex items-center mb-2">
                <span class="px-2 py-1 text-xs rounded-full mr-2" :class="report.typeClass">{{ report.type }}</span>
                <div class="text-xs text-gray-500">
                  {{ report.publishTime }}
                </div>
              </div>
              <h3 class="text-md font-medium text-gray-900 mb-2 line-clamp-2">
                {{ report.title }}
              </h3>
              <div class="flex justify-between items-center">
                <div class="flex items-center text-xs text-gray-500">
                  <i class="fas fa-eye mr-1"></i>
                  <span>{{ report.readCount }}</span>
                </div>
                <div class="flex items-center text-xs text-gray-500">
                  <i class="fas fa-download mr-1"></i>
                  <span>{{ report.downloadCount }}</span>
                </div>
              </div>
            </el-card>
          </div>
        </div>

        <!-- 热门报告详情弹窗 -->
        <el-dialog v-model="showHotReportDetailModal" title="报告详情" width="70%"
          :before-close="closeHotReportDetailModal">
          <div v-if="hotReportDetail" class="p-4">
            <div class="mb-6">
              <div class="flex items-start">
                <div class="w-32 h-40 mr-6 rounded-lg overflow-hidden flex-shrink-0">
                  <img :src="hotReportDetail.coverImage" alt="报告封面" class="w-full h-full object-cover" />
                </div>
                <div class="flex-1">
                  <h2 class="text-xl font-bold text-gray-800 mb-2">{{ hotReportDetail.title }}</h2>
                  <div class="flex items-center mb-4">
                    <span class="px-3 py-1 text-sm rounded-full mr-3" :class="hotReportDetail.typeClass">{{
                      hotReportDetail.type }}</span>
                    <span class="text-sm text-gray-500">{{ hotReportDetail.publishTime }}</span>
                  </div>
                  <div class="flex items-center text-sm text-gray-600 mb-4">
                    <div class="flex items-center mr-6">
                      <i class="fas fa-eye mr-2"></i>
                      <span>阅读量: {{ hotReportDetail.readCount }}</span>
                    </div>
                    <div class="flex items-center">
                      <i class="fas fa-download mr-2"></i>
                      <span>下载量: {{ hotReportDetail.downloadCount }}</span>
                    </div>
                  </div>
                  <p class="text-gray-700">
                    这是一份关于钢铁企业安全生产的重要报告，详细分析了当前的安全状况和未来发展趋势。报告通过数据分析和实地调研，提出了多项改进建议，对提升企业安全管理水平具有重要意义。</p>
                </div>
              </div>
            </div>

            <div class="border-t pt-4">
              <h3 class="text-lg font-semibold text-gray-800 mb-4">报告内容概览</h3>
              <div class="bg-gray-50 rounded-lg p-4">
                <h4 class="font-medium text-gray-800 mb-2">一、引言</h4>
                <p class="text-gray-700 mb-4">本报告基于对多家钢铁企业的安全生产情况进行全面调研，结合行业发展趋势，分析当前存在的问题并提出解决方案。</p>

                <h4 class="font-medium text-gray-800 mb-2">二、现状分析</h4>
                <p class="text-gray-700 mb-4">通过对安全生产数据的收集和分析，我们发现钢铁企业在安全管理方面存在以下几个主要问题...</p>

                <h4 class="font-medium text-gray-800 mb-2">三、改进建议</h4>
                <p class="text-gray-700">针对以上问题，我们提出以下改进建议...</p>
              </div>
            </div>
          </div>

          <template #footer>
            <div class="flex justify-end space-x-3">
              <el-button @click="closeHotReportDetailModal">关闭</el-button>
              <el-button type="primary" @click="downloadHotReport">下载报告</el-button>
            </div>
          </template>
        </el-dialog>

        <!-- 新建报告弹窗 -->
        <div v-if="showNewReportModal"
          class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div class="bg-white rounded-lg p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <div class="flex justify-between items-center mb-6">
              <h3 class="text-lg font-bold text-gray-800">新建专题报告</h3>
              <button @click="closeNewReportModal" class="text-gray-500 hover:text-gray-700 cursor-pointer"
                :disabled="isSubmitting">
                <i class="fas fa-times"></i>
              </button>
            </div>
            <form @submit.prevent="submitNewReport">
              <div class="grid grid-cols-2 gap-4 mb-4">
                <!-- 报告标题 -->
                <div class="col-span-2">
                  <label class="block text-sm font-medium text-gray-700 mb-2">报告标题 *</label>
                  <input type="text" v-model="newReport.title"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    :class="{ 'border-red-500': formErrors.title }" placeholder="请输入报告标题" maxlength="100" required />
                  <div class="flex justify-between">
                    <div v-if="formErrors.title" class="text-red-500 text-xs mt-1">
                      {{ formErrors.title }}
                    </div>
                    <div class="text-gray-400 text-xs mt-1 ml-auto">
                      {{ newReport.title.length }}/100
                    </div>
                  </div>
                </div>

                <!-- 报告类型 -->
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">报告类型 *</label>
                  <select v-model="newReport.type"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    :class="{ 'border-red-500': formErrors.type }" required>
                    <option value="" disabled hidden>请选择报告类型</option>
                    <option value="月度报告">月度报告</option>
                    <option value="季度报告">季度报告</option>
                    <option value="半年报告">半年报告</option>
                    <option value="年度报告">年度报告</option>
                    <option value="专项报告">专项报告</option>
                    <option value="研究报告">研究报告</option>
                    <option value="评估报告">评估报告</option>
                    <option value="指导报告">指导报告</option>
                  </select>
                  <div v-if="formErrors.type" class="text-red-500 text-xs mt-1">
                    {{ formErrors.type }}
                  </div>
                </div>

                <!-- 作者 -->
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">作者 *</label>
                  <input type="text" v-model="newReport.author"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    :class="{ 'border-red-500': formErrors.author }" placeholder="请输入作者" maxlength="50" required />
                  <div class="flex justify-between">
                    <div v-if="formErrors.author" class="text-red-500 text-xs mt-1">
                      {{ formErrors.author }}
                    </div>
                    <div class="text-gray-400 text-xs mt-1 ml-auto">
                      {{ newReport.author.length }}/50
                    </div>
                  </div>
                </div>

                <!-- 发布时间 -->
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">发布时间 *</label>
                  <input type="date" v-model="newReport.publishTime"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    :class="{ 'border-red-500': formErrors.publishTime }" :max="getCurrentDate()" required />
                  <div v-if="formErrors.publishTime" class="text-red-500 text-xs mt-1">
                    {{ formErrors.publishTime }}
                  </div>
                </div>

                <!-- 部门 -->
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">部门</label>
                  <select v-model="newReport.department"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="" disabled hidden>请选择部门</option>
                    <option value="安全生产部">安全生产部</option>
                    <option value="设备管理部">设备管理部</option>
                    <option value="技术研发部">技术研发部</option>
                    <option value="人力资源部">人力资源部</option>
                  </select>
                </div>

                <!-- 报告摘要 -->
                <div class="col-span-2">
                  <label class="block text-sm font-medium text-gray-700 mb-2">报告摘要</label>
                  <textarea v-model="newReport.summary"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    :class="{ 'border-red-500': formErrors.summary }" rows="3" placeholder="请输入报告摘要"
                    maxlength="500"></textarea>
                  <div class="flex justify-between">
                    <div v-if="formErrors.summary" class="text-red-500 text-xs mt-1">
                      {{ formErrors.summary }}
                    </div>
                    <div class="text-gray-400 text-xs mt-1 ml-auto">
                      {{ newReport.summary.length }}/500
                    </div>
                  </div>
                </div>

                <!-- 报告封面 -->
                <div class="col-span-2">
                  <label class="block text-sm font-medium text-gray-700 mb-2">报告封面链接</label>
                  <input type="url" v-model="newReport.coverImage"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="请输入封面图片链接" />
                </div>

                <!-- 标签 -->
                <div class="col-span-2">
                  <label class="block text-sm font-medium text-gray-700 mb-2">标签</label>
                  <div class="flex flex-wrap gap-2">
                    <span v-for="(tag, index) in newReport.tags" :key="index"
                      class="inline-flex items-center px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full">
                      {{ tag }}
                      <button type="button" @click="removeTag(index)" class="ml-1 text-blue-600 hover:text-blue-800"
                        :disabled="isSubmitting">
                        <i class="fas fa-times text-xs"></i>
                      </button>
                    </span>
                    <input type="text" v-model="newTag" @keydown.enter.prevent="addTag"
                      class="flex-1 px-2 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
                      placeholder="输入标签后按回车添加" :disabled="isSubmitting" />
                  </div>
                </div>
              </div>

              <div class="border-t border-gray-200 pt-4">
                <div class="flex justify-between">
                  <button type="button" @click="closeNewReportModal"
                    class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors duration-200"
                    :disabled="isSubmitting">
                    取消
                  </button>
                  <button type="submit"
                    class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors duration-200 flex items-center"
                    :disabled="isSubmitting">
                    <i class="fas fa-spinner fa-spin mr-2" v-if="isSubmitting"></i>
                    {{ isSubmitting ? "提交中..." : "创建报告" }}
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
        <!-- 删除确认弹窗 -->
        <div v-if="showDeleteConfirmModal"
          class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div class="bg-white rounded-lg p-6 w-96">
            <div class="flex justify-between items-center mb-4">
              <h3 class="text-lg font-bold text-gray-800">确认删除</h3>
              <button @click="closeDeleteConfirmModal" class="text-gray-500 hover:text-gray-700 cursor-pointer"
                :disabled="isDeleting">
                <i class="fas fa-times"></i>
              </button>
            </div>
            <div class="mb-6">
              <div class="flex items-center justify-center w-16 h-16 bg-red-100 rounded-full mx-auto mb-4">
                <i class="fas fa-exclamation-triangle text-red-600 text-2xl"></i>
              </div>
              <p class="text-center text-gray-700 mb-2">确定要删除此报告吗？</p>
              <p class="text-center text-sm text-gray-500">
                报告标题：{{ reportToDelete?.title }}
              </p>
              <p class="text-center text-sm text-gray-500">
                此操作不可恢复，请谨慎操作！
              </p>
            </div>
            <div class="border-t border-gray-200 pt-4">
              <div class="flex justify-between space-x-3">
                <button type="button" @click="closeDeleteConfirmModal"
                  class="flex-1 px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors duration-200"
                  :disabled="isDeleting">
                  取消
                </button>
                <button type="button" @click="deleteReport"
                  class="flex-1 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors duration-200 flex items-center justify-center"
                  :disabled="isDeleting">
                  <i class="fas fa-spinner fa-spin mr-2" v-if="isDeleting"></i>
                  {{ isDeleting ? "删除中..." : "确认删除" }}
                </button>
              </div>
            </div>
          </div>
        </div>
        <!-- 报告详情弹窗 -->
        <div v-if="showReportDetailModal"
          class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"
          @click.self="closeReportDetail">
          <div class="bg-white rounded-lg w-full max-w-4xl max-h-[90vh] overflow-hidden flex flex-col">
            <!-- 弹窗头部 -->
            <div class="flex justify-between items-center p-6 border-b border-gray-200 bg-white sticky top-0 z-10">
              <div class="flex items-center">
                <div class="w-10 h-10 rounded-full flex items-center justify-center mr-3" :class="reportDetail?.iconBg">
                  <i :class="reportDetail?.icon + ' ' + reportDetail?.iconColor"></i>
                </div>
                <div>
                  <h3 class="text-xl font-bold text-gray-800">
                    {{ reportDetail?.title }}
                  </h3>
                  <p class="text-sm text-gray-600">
                    {{ reportDetail?.author }} • {{ reportDetail?.publishTime }}
                  </p>
                </div>
              </div>
              <button @click="closeReportDetail"
                class="text-gray-500 hover:text-gray-700 cursor-pointer p-2 rounded-lg hover:bg-gray-100 transition-colors">
                <i class="fas fa-times text-lg"></i>
              </button>
            </div>
            <!-- 弹窗内容 -->
            <div class="flex-1 overflow-y-auto p-6">
              <div class="grid grid-cols-3 gap-6 mb-6">
                <!-- 基本信息 -->
                <div class="col-span-2">
                  <div class="bg-gray-50 rounded-lg p-4">
                    <h4 class="font-semibold text-gray-800 mb-3">
                      报告基本信息
                    </h4>
                    <div class="grid grid-cols-2 gap-4 text-sm">
                      <div>
                        <span class="text-gray-500">报告类型：</span>
                        <span class="font-medium">{{
                          reportDetail?.type
                        }}</span>
                      </div>
                      <div>
                        <span class="text-gray-500">发布时间：</span>
                        <span class="font-medium">{{
                          reportDetail?.publishTime
                        }}</span>
                      </div>
                      <div>
                        <span class="text-gray-500">阅读量：</span>
                        <span class="font-medium">{{
                          reportDetail?.readCount
                        }}</span>
                      </div>
                      <div>
                        <span class="text-gray-500">下载量：</span>
                        <span class="font-medium">{{
                          reportDetail?.downloadCount
                        }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <!-- 报告内容预览 -->
              <div class="bg-white border border-gray-200 rounded-lg p-6">
                <h4 class="font-semibold text-gray-800 mb-4">报告内容预览</h4>
                <div class="prose max-w-none">
                  <p class="text-gray-700 leading-relaxed">
                    这是一份关于{{
                      reportDetail?.type
                    }}的详细分析报告。报告包含了详细的数据分析、趋势预测和改进建议。
                    主要内容包括：
                  </p>
                  <ul class="list-disc list-inside mt-3 text-gray-700 space-y-1">
                    <li>当前行业现状分析</li>
                    <li>关键指标数据统计</li>
                    <li>风险评估与预测</li>
                    <li>改进措施建议</li>
                    <li>未来发展趋势</li>
                  </ul>
                  <div class="mt-4 p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                    <p class="text-sm text-yellow-800">
                      <i class="fas fa-info-circle mr-2"></i>
                      此为报告内容预览，完整报告请下载查看。
                    </p>
                  </div>
                </div>
              </div>
              <!-- 相关标签 -->
              <div class="mt-6">
                <h4 class="font-semibold text-gray-800 mb-3">报告标签</h4>
                <div class="flex flex-wrap gap-2">
                  <span v-for="(tag, index) in reportDetail?.tags || [
                    '安全生产',
                    '数据分析',
                    '行业报告',
                  ]" :key="index"
                    class="px-3 py-1 bg-gray-100 text-gray-700 text-sm rounded-full border border-gray-200">
                    {{ tag }}
                  </span>
                </div>
              </div>
            </div>
            <!-- 弹窗底部操作 -->
            <div class="border-t border-gray-200 p-4 bg-gray-50">
              <div class="flex justify-between items-center">
                <div class="text-sm text-gray-600">
                  <span class="flex items-center">
                    <i class="fas fa-clock mr-1"></i>
                    最后更新：{{ currentTime }}
                  </span>
                </div>
                <div class="flex space-x-3">
                  <button @click="downloadReportFromDetail(reportDetail)"
                    class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors flex items-center"
                    :disabled="isDownloading">
                    <i class="fas fa-download mr-2"></i>
                    {{ isDownloading ? "下载中..." : "下载报告" }}
                  </button>
                  <button @click="markAsRead(reportDetail)"
                    class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center"
                    v-if="reportDetail && !reportDetail.isRead">
                    <i class="fas fa-check mr-2"></i>
                    标记为已读
                  </button>
                </div>
              </div>
              <!-- 下载进度条 -->
              <div v-if="isDownloading" class="mt-3">
                <div class="flex justify-between text-xs text-gray-600 mb-1">
                  <span>下载进度</span>
                  <span>{{ downloadProgress }}%</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2">
                  <div class="bg-green-600 h-2 rounded-full transition-all duration-300"
                    :style="{ width: downloadProgress + '%' }"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>
<script>
import * as echarts from "echarts";
import Header from "../components/Header.vue";
import Pagination from "../components/Pagination.vue";
import { ElMessage, ElMessageBox } from "element-plus";

export default {
  components: {
    Header,
    Pagination,
  },
  data() {
    return {
      currentTime: "2025-07-08 15:32:45",
      currentPeriod: "month",
      showShareModal: false,
      showQRCodeModal: false, // 二维码弹窗
      showNewReportModal: false, // 控制新建报告弹窗显示
      showDeleteConfirmModal: false, // 删除确认弹窗
      isSubmitting: false, // 提交状态
      isDeleting: false, // 删除状态
      // 添加下拉菜单显示控制
      showSortDropdown: false,
      showReadStatusDropdown: false,
      showReportTypeDropdown: false,
      showReportDetailModal: false, // 报告详情弹窗
      showReportTypeDropdown: false, // 添加显示控制
      reportDetail: null, // 当前查看的报告详情
      showHotReportDetailModal: false, // 热门报告详情弹窗
      hotReportDetail: null, // 当前查看的热门报告详情
      downloadProgress: 0, // 下载进度
      isDownloading: false, // 下载状态
      newTag: "", // 临时标签输入
      formErrors: {}, // 表单错误信息
      currentReport: {},
      reportToDelete: null, // 待删除的报告
      shareLink: "https://steel-safety.example.com/reports/share/123456",
      totalReports: 128,
      // 添加分页相关数据
      currentPage: 1,
      pageSize: 10,
      // 添加排序和筛选相关数据
      sortField: "publishTime", // 默认按发布时间排序
      sortOrder: "desc", // 默认降序
      readStatus: "all",
      reportType: "all",
      // 搜索相关数据
      searchKeyword: "", // 搜索关键词
      startDate: "", // 开始日期
      endDate: "", // 结束日期
      // 临时日期变量，用于存储用户选择的日期，但不立即应用筛选
      tempStartDate: "", // 临时开始日期
      tempEndDate: "", // 临时结束日期
      appliedStartDate: "", // 已应用的开始日期
      appliedEndDate: "", // 已应用的结束日期
      isDateFilterApplied: false, // 是否应用了日期筛选
      // 新建报告表单数据
      newReport: {
        title: "",
        type: "",
        author: "",
        department: "",
        publishTime: this.getCurrentDate(),
        summary: "",
        coverImage: "",
        tags: [],
      },
      mainMenus: [
        {
          name: "监测报警",
          icon: "fas fa-bell",
          expanded: false,
          active: false,
          subMenus: [
            { name: "数据汇聚功能", active: false, link: "/data-aggregation" },
            {
              name: "监测指标统计",
              active: false,
              link: "/monitoring-indicators",
            },
            { name: "区域化展示", active: false, link: "/regional-display" },
          ],
        },
        {
          name: "风险研判",
          icon: "fas fa-exclamation-triangle",
          expanded: false,
          active: false,
          subMenus: [
            { name: '智能风险评估', active: false, link: '/intelligent-risk-assessment' },
            { name: '预警信息推送', active: false, link: '/risk-warning-push' },
            { name: '风险管理与分析', active: true, link: '/risk-analysis' },
          ]
        },
        {
          name: "在线巡查",
          icon: "fas fa-search",
          expanded: false,
          active: false,
          subMenus: [
            {
              name: "企业信息汇总",
              active: false,
              link: "/summary-information",
            },
            { name: "巡查功能", active: false, link: "/patrol" },
            { name: "检索功能", active: false, link: "/search" },
            { name: "一屏汇聚展示", active: false, link: "/screen-display" },
          ],
        },
        {
          name: "综合分析",
          icon: "fas fa-chart-line",
          expanded: true,
          active: true,
          subMenus: [
            { name: "联网与设备分析", active: false, link: "/equipment" },
            { name: "应用情况分析", active: false, link: "/application" },
            { name: "数据质量分析", active: false, link: "/data-quality" },
            { name: "定期专题报告", active: true, link: "/report" },
          ],
        },
        {
          name: "系统管理",
          icon: "fas fa-cog",
          expanded: false,
          active: false,
          subMenus: [
            { name: "用户权限管理", active: false, link: "/user-permission" },
            { name: "系统配置管理", active: false, link: "/system-manage" },
            { name: "数据管理", active: true, link: "/data-manage" },
            { name: "系统监控与维护", active: false, link: "/monitoring" },
          ],
        },
      ],
      reportList: JSON.parse(localStorage.getItem("reportList")) || [
        {
          id: 1,
          title: "2025年第二季度钢铁行业安全生产形势分析报告",
          author: "安全生产部 - 张明",
          type: "季度报告",
          typeClass: "bg-blue-100 text-blue-800",
          icon: "fas fa-file-alt",
          iconBg: "bg-blue-100",
          iconColor: "text-blue-600",
          publishTime: "2025-07-05",
          isRead: false,
          readCount: 156,
          downloadCount: 42,
        },
        {
          id: 2,
          title: "高炉煤气安全监测系统运行状况专题报告",
          author: "设备管理部 - 李强",
          type: "专项报告",
          typeClass: "bg-green-100 text-green-800",
          icon: "fas fa-file-alt",
          iconBg: "bg-green-100",
          iconColor: "text-green-600",
          publishTime: "2025-07-01",
          isRead: true,
          readCount: 203,
          downloadCount: 68,
        },
        {
          id: 3,
          title: "钢铁企业危险化学品管理现状与改进建议",
          author: "安全生产部 - 王刚",
          type: "专项报告",
          typeClass: "bg-green-100 text-green-800",
          icon: "fas fa-file-alt",
          iconBg: "bg-green-100",
          iconColor: "text-green-600",
          publishTime: "2025-06-28",
          isRead: true,
          readCount: 178,
          downloadCount: 53,
        },
        {
          id: 4,
          title: "2025年上半年安全生产事故分析与预防措施",
          author: "安全生产部 - 赵敏",
          type: "半年报告",
          typeClass: "bg-purple-100 text-purple-800",
          icon: "fas fa-file-alt",
          iconBg: "bg-purple-100",
          iconColor: "text-purple-600",
          publishTime: "2025-06-25",
          isRead: false,
          readCount: 245,
          downloadCount: 89,
        },
        {
          id: 5,
          title: "特种设备安全监管智能化升级专题研究",
          author: "技术研发部 - 陈伟",
          type: "研究报告",
          typeClass: "bg-yellow-100 text-yellow-800",
          icon: "fas fa-file-alt",
          iconBg: "bg-yellow-100",
          iconColor: "text-yellow-600",
          publishTime: "2025-06-20",
          isRead: true,
          readCount: 132,
          downloadCount: 47,
        },
        {
          id: 6,
          title: "钢铁企业职业健康安全管理体系评估报告",
          author: "人力资源部 - 林芳",
          type: "评估报告",
          typeClass: "bg-red-100 text-red-800",
          icon: "fas fa-file-alt",
          iconBg: "bg-red-100",
          iconColor: "text-red-600",
          publishTime: "2025-06-15",
          isRead: false,
          readCount: 167,
          downloadCount: 38,
        },
        {
          id: 7,
          title: "2025年6月份安全生产监督检查情况通报",
          author: "安全生产部 - 张明",
          type: "月度报告",
          typeClass: "bg-indigo-100 text-indigo-800",
          icon: "fas fa-file-alt",
          iconBg: "bg-indigo-100",
          iconColor: "text-indigo-600",
          publishTime: "2025-06-10",
          isRead: true,
          readCount: 198,
          downloadCount: 56,
        },
        {
          id: 8,
          title: "高温作业环境安全防护措施专题研究",
          author: "安全生产部 - 王刚",
          type: "研究报告",
          typeClass: "bg-yellow-100 text-yellow-800",
          icon: "fas fa-file-alt",
          iconBg: "bg-yellow-100",
          iconColor: "text-yellow-600",
          publishTime: "2025-06-05",
          isRead: true,
          readCount: 145,
          downloadCount: 42,
        },
      ],
      hotReports: [
        {
          id: 101,
          title: "钢铁行业安全生产智能化转型路径研究",
          type: "研究报告",
          typeClass: "bg-yellow-100 text-yellow-800",
          publishTime: "2025-06-15",
          readCount: 356,
          downloadCount: 128,
          coverImage:
            "https://readdy.ai/api/search-image?query=Professional%20research%20report%20cover%20with%20steel%20industry%20safety%20theme%2C%20showing%20modern%20factory%20with%20blue%20gradient%20background%2C%20minimalist%20design%20with%20data%20visualization%20elements%20and%20safety%20icons&width=400&height=240&seq=101&orientation=landscape",
        },
        {
          id: 102,
          title: "智能安全帽应用效果评估与优化建议",
          type: "评估报告",
          typeClass: "bg-red-100 text-red-800",
          publishTime: "2025-05-28",
          readCount: 312,
          downloadCount: 95,
          coverImage:
            "https://readdy.ai/api/search-image?query=Smart%20safety%20helmet%20in%20steel%20factory%20environment%2C%20professional%20report%20cover%20with%20blue%20background%2C%20showing%20worker%20wearing%20intelligent%20safety%20equipment%20with%20digital%20interface%2C%20high%20tech%20industrial%20safety%20concept&width=400&height=240&seq=102&orientation=landscape",
        },
        {
          id: 103,
          title: "基于大数据的安全风险预警模型构建",
          type: "研究报告",
          typeClass: "bg-yellow-100 text-yellow-800",
          publishTime: "2025-06-02",
          readCount: 289,
          downloadCount: 87,
          coverImage:
            "https://readdy.ai/api/search-image?query=Data%20visualization%20dashboard%20showing%20safety%20risk%20prediction%20model%2C%20professional%20report%20cover%20with%20blue%20gradient%20background%2C%20abstract%20digital%20data%20streams%20and%20warning%20indicators%2C%20high%20tech%20industrial%20monitoring%20system%20interface&width=400&height=240&seq=103&orientation=landscape",
        },
        {
          id: 104,
          title: "钢铁企业安全生产标准化建设指南",
          type: "指导报告",
          typeClass: "bg-blue-100 text-blue-800",
          publishTime: "2025-05-15",
          readCount: 276,
          downloadCount: 104,
          coverImage:
            "https://readdy.ai/api/search-image?query=Steel%20factory%20safety%20standardization%20guide%20cover%2C%20professional%20blue%20background%20with%20organized%20industrial%20equipment%20layout%2C%20safety%20procedure%20diagrams%20and%20standardization%20icons%2C%20modern%20industrial%20management%20concept&width=400&height=240&seq=104&orientation=landscape",
        },
      ],
      // 排序选项
      sortOptions: [
        { label: "发布时间(最新)", value: "publishTime_desc" },
        { label: "发布时间(最早)", value: "publishTime_asc" },
        { label: "阅读量(最多)", value: "readCount_desc" },
        { label: "阅读量(最少)", value: "readCount_asc" },
        { label: "下载量(最多)", value: "downloadCount_desc" },
        { label: "下载量(最少)", value: "downloadCount_asc" },
      ],
      // 阅读状态选项
      readStatusOptions: [
        { label: "全部", value: "all" },
        { label: "已读", value: "read" },
        { label: "未读", value: "unread" },
      ],
      reportTypeOptions: [
        { label: "全部类型", value: "all" },
        { label: "月度报告", value: "月度报告" },
        { label: "季度报告", value: "季度报告" },
        { label: "半年报告", value: "半年报告" },
        { label: "年度报告", value: "年度报告" },
        { label: "专项报告", value: "专项报告" },
        { label: "研究报告", value: "研究报告" },
        { label: "评估报告", value: "评估报告" },
        { label: "指导报告", value: "指导报告" },
      ],
    };
  },
  computed: {
    // 添加计算属性来处理分页和筛选后的数据
    filteredAndPagedReports() {
      let filteredReports = [...this.reportList];

      // 按时间范围筛选（修复日期比较逻辑）
      if (this.isDateFilterApplied && (this.appliedStartDate || this.appliedEndDate)) {
        filteredReports = filteredReports.filter((report) => {
          const reportDate = new Date(report.publishTime);
          reportDate.setHours(0, 0, 0, 0); // 标准化时间为当天开始

          let passStart = true;
          let passEnd = true;

          if (this.appliedStartDate) {
            const start = new Date(this.appliedStartDate);
            start.setHours(0, 0, 0, 0);
            passStart = reportDate >= start;
          }

          if (this.appliedEndDate) {
            const end = new Date(this.appliedEndDate);
            end.setHours(23, 59, 59, 999); // 设置为当天结束
            passEnd = reportDate <= end;
          }

          return passStart && passEnd;
        });
      }

      // 按阅读状态筛选
      if (this.readStatus === "read") {
        filteredReports = filteredReports.filter((report) => report.isRead);
      } else if (this.readStatus === "unread") {
        filteredReports = filteredReports.filter((report) => !report.isRead);
      }

      // 按报告类型筛选
      if (this.reportType !== "all") {
        filteredReports = filteredReports.filter(
          (report) => report.type === this.reportType
        );
      }

      // 按关键词搜索
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase().trim();
        filteredReports = filteredReports.filter(
          (report) =>
            report.title.toLowerCase().includes(keyword) ||
            report.author.toLowerCase().includes(keyword)
        );
      }

      // 排序
      filteredReports.sort((a, b) => {
        let aValue, bValue;
        switch (this.sortField) {
          case "publishTime":
            aValue = new Date(a.publishTime);
            bValue = new Date(b.publishTime);
            break;
          case "readCount":
            aValue = a.readCount;
            bValue = b.readCount;
            break;
          case "downloadCount":
            aValue = a.downloadCount;
            bValue = b.downloadCount;
            break;
          default:
            return 0;
        }

        if (this.sortOrder === "asc") {
          return aValue > bValue ? 1 : -1;
        } else {
          return aValue < bValue ? 1 : -1;
        }
      });

      // 分页
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return filteredReports.slice(start, end);
    },
    // 计算总页数
    totalPages() {
      // 先进行筛选
      let filteredReports = [...this.reportList];
      // 按阅读状态筛选
      if (this.readStatus === "read") {
        filteredReports = filteredReports.filter((report) => report.isRead);
      } else if (this.readStatus === "unread") {
        filteredReports = filteredReports.filter((report) => !report.isRead);
      }
      return Math.ceil(filteredReports.length / this.pageSize);
    },
    // 计算筛选后的总报告数
    filteredTotalReports() {
      let filteredReports = [...this.reportList];

      // 按时间范围筛选
      if (this.isDateFilterApplied && (this.appliedStartDate || this.appliedEndDate)) {
        filteredReports = filteredReports.filter((report) => {
          const reportDate = new Date(report.publishTime);
          reportDate.setHours(0, 0, 0, 0);

          let passStart = true;
          let passEnd = true;
          if (this.appliedStartDate) {
            const start = new Date(this.appliedStartDate);
            start.setHours(0, 0, 0, 0);
            passStart = reportDate >= start;
          }
          if (this.appliedEndDate) {
            const end = new Date(this.appliedEndDate);
            end.setHours(23, 59, 59, 999);
            passEnd = reportDate <= end;
          }
          return passStart && passEnd;
        });
      }

      // 按阅读状态筛选
      if (this.readStatus === "read") {
        filteredReports = filteredReports.filter((report) => report.isRead);
      } else if (this.readStatus === "unread") {
        filteredReports = filteredReports.filter((report) => !report.isRead);
      }

      // 按报告类型筛选
      if (this.reportType !== "all") {
        filteredReports = filteredReports.filter(
          (report) => report.type === this.reportType
        );
      }

      // 按关键词搜索
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase().trim();
        filteredReports = filteredReports.filter(
          (report) =>
            report.title.toLowerCase().includes(keyword) ||
            report.author.toLowerCase().includes(keyword)
        );
      }

      return filteredReports.length;
    },
    // 获取当前选中的报告类型显示文本
    currentReportTypeLabel() {
      const option = this.reportTypeOptions.find(
        (opt) => opt.value === this.reportType
      );
      return option ? option.label : "全部类型";
    },
    // 根据筛选条件计算报告分类分布
    filteredReportCategoryData() {
      // 先进行所有筛选（与报告列表相同的筛选逻辑）
      let filteredReports = [...this.reportList];

      // 按阅读状态筛选
      if (this.readStatus === "read") {
        filteredReports = filteredReports.filter((report) => report.isRead);
      } else if (this.readStatus === "unread") {
        filteredReports = filteredReports.filter((report) => !report.isRead);
      }

      // 按报告类型筛选
      if (this.reportType !== "all") {
        filteredReports = filteredReports.filter(
          (report) => report.type === this.reportType
        );
      }

      // 按关键词搜索
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase().trim();
        filteredReports = filteredReports.filter(
          (report) =>
            report.title.toLowerCase().includes(keyword) ||
            report.author.toLowerCase().includes(keyword)
        );
      }

      // 按时间范围筛选
      if (this.isDateFilterApplied && (this.appliedStartDate || this.appliedEndDate)) {
        filteredReports = filteredReports.filter((report) => {
          const reportDate = new Date(report.publishTime);
          reportDate.setHours(0, 0, 0, 0);

          let passStart = true;
          let passEnd = true;
          if (this.appliedStartDate) {
            const start = new Date(this.appliedStartDate);
            start.setHours(0, 0, 0, 0);
            passStart = reportDate >= start;
          }
          if (this.appliedEndDate) {
            const end = new Date(this.appliedEndDate);
            end.setHours(23, 59, 59, 999);
            passEnd = reportDate <= end;
          }
          return passStart && passEnd;
        });
      }

      // 统计各类型的报告数量
      const categoryCount = {};
      const allTypes = [
        "月度报告", "季度报告", "半年报告", "年度报告",
        "专项报告", "研究报告", "评估报告", "指导报告"
      ];

      // 初始化所有类型为0
      allTypes.forEach(type => {
        categoryCount[type] = 0;
      });

      // 统计筛选后的报告类型数量
      filteredReports.forEach(report => {
        if (categoryCount.hasOwnProperty(report.type)) {
          categoryCount[report.type]++;
        }
      });

      // 转换为图表数据格式
      const chartData = allTypes.map(type => ({
        value: categoryCount[type],
        name: type,
        itemStyle: { color: this.getChartColor(type) }
      })).filter(item => item.value > 0); // 只显示有数据的类型

      return chartData;
    },
    // 基于筛选数据的趋势图表数据
    filteredTrendData() {
      // 获取筛选后的报告数据
      let filteredReports = [...this.reportList];

      // 应用日期筛选
      if (this.isDateFilterApplied && (this.appliedStartDate || this.appliedEndDate)) {
        filteredReports = filteredReports.filter((report) => {
          const reportDate = new Date(report.publishTime);
          let passStart = true;
          let passEnd = true;
          if (this.appliedStartDate) {
            const start = new Date(this.appliedStartDate);
            passStart = reportDate >= start;
          }
          if (this.appliedEndDate) {
            const end = new Date(this.appliedEndDate);
            end.setHours(23, 59, 59, 999);
            passEnd = reportDate <= end;
          }
          return passStart && passEnd;
        });
      }

      // 根据当前周期生成图表数据
      return this.generateTrendDataByPeriod(filteredReports, this.currentPeriod);
    }
  },
  mounted() {
    this.initReportCategoryChart();
    this.initReportReadingTrendChart();
    // 响应窗口大小变化
    window.addEventListener("resize", this.handleResize);
    // 更新时间
    this.updateCurrentTime();
    setInterval(this.updateCurrentTime, 1000);
    // 初始化时从本地存储加载数据并更新统计
    this.loadReportData();
    // 添加点击事件监听器来关闭下拉菜单
    document.addEventListener("click", this.closeDropdowns);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
    clearInterval(this.timeInterval);
  },
  watch: {
    // 监听筛选条件变化，更新图表
    filteredReportCategoryData: {
      handler(newData) {
        this.$nextTick(() => {
          this.updateReportCategoryChart(newData);
        });
      },
      immediate: true
    },

    // 监听其他筛选条件的变化，触发图表更新
    readStatus() {
      this.updateCharts();
    },
    reportType() {
      this.updateCharts();
    },
    searchKeyword() {
      this.updateCharts();
    }
  },
  methods: {
    // 处理搜索
    handleSearch() {
      this.currentPage = 1; // 搜索后重置到第一页
      this.updateCharts();
    },
    // 清空搜索
    clearSearch() {
      this.searchKeyword = "";
      this.currentPage = 1;
      this.updateCharts();
    },
    // 应用日期筛选
    applyDateFilter() {
      // 验证日期范围
      if (this.tempStartDate && this.tempEndDate) {
        const start = new Date(this.tempStartDate);
        const end = new Date(this.tempEndDate);

        if (start > end) {
          ElMessage.error('开始日期不能晚于结束日期');
          return;
        }
      }

      // 应用筛选条件
      this.appliedStartDate = this.tempStartDate;
      this.appliedEndDate = this.tempEndDate;
      this.isDateFilterApplied = true;

      // 重置到第一页
      this.currentPage = 1;

      // 强制更新计算属性
      this.$forceUpdate();

      // 触发图表更新
      this.updateCharts();

      // 显示筛选结果统计
      const filteredCount = this.filteredTotalReports;
      ElMessage.success(`筛选完成，共找到 ${filteredCount} 份报告`);
    },
    // 清除日期筛选
    clearDateFilter() {
      this.tempStartDate = "";
      this.tempEndDate = "";
      this.appliedStartDate = "";
      this.appliedEndDate = "";
      this.isDateFilterApplied = false;
      this.currentPage = 1;

      // 强制更新计算属性
      this.$forceUpdate();

      this.updateCharts();
      ElMessage.info('日期筛选已清除');
    },
    // 分页相关方法
    handlePageChange(page) {
      this.currentPage = page;
    },
    handlePageSizeChange(size) {
      this.pageSize = size;
      // 重置到第一页
      this.currentPage = 1;
    },
    // 排序和筛选相关方法
    toggleSortDropdown() {
      // 关闭其他下拉菜单
      this.showReadStatusDropdown = false;
      this.showReportTypeDropdown = false;
      // 切换当前下拉菜单
      this.showSortDropdown = !this.showSortDropdown;
    },
    selectSort(value) {
      const [field, order] = value.split("_");
      this.sortField = field;
      this.sortOrder = order;
      this.showSortDropdown = false;
      // 重置到第一页
      this.currentPage = 1;
    },
    getCurrentSortValue() {
      return `${this.sortField}_${this.sortOrder}`;
    },
    toggleReadStatusDropdown() {
      // 关闭其他下拉菜单
      this.showSortDropdown = false;
      this.showReportTypeDropdown = false;
      // 切换当前下拉菜单
      this.showReadStatusDropdown = !this.showReadStatusDropdown;
    },
    selectReadStatus(value) {
      this.readStatus = value;
      this.showReadStatusDropdown = false;
      // 重置到第一页
      this.currentPage = 1;
      this.updateCharts();
    },
    toggleReportTypeDropdown() {
      // 关闭其他下拉菜单
      this.showSortDropdown = false;
      this.showReadStatusDropdown = false;
      // 切换当前下拉菜单
      this.showReportTypeDropdown = !this.showReportTypeDropdown;
    },
    selectReportType(value) {
      this.reportType = value;
      this.showReportTypeDropdown = false;
      // 重置到第一页
      this.currentPage = 1;
      this.updateCharts();
    },
    // 点击页面其他地方关闭下拉菜单的方法
    closeDropdowns(event) {
      // 检查点击事件是否发生在下拉菜单相关的元素上
      if (!event.target.closest(".relative")) {
        this.showSortDropdown = false;
        this.showReadStatusDropdown = false;
        this.showReportTypeDropdown = false;
      }
    },
    // 获取当前日期（YYYY-MM-DD格式）
    getCurrentDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    // 获取图表颜色
    getChartColor(type) {
      const colorMap = {
        "月度报告": "#4299e1",
        "季度报告": "#48bb78",
        "半年报告": "#9f7aea",
        "年度报告": "#f56565",
        "专项报告": "#38b2ac",
        "研究报告": "#ecc94b",
        "评估报告": "#ed8936",
        "指导报告": "#667eea"
      };
      return colorMap[type] || "#a0aec0";
    },
    // 更新报告分类分布图表
    updateReportCategoryChart(chartData = null) {
      if (!this.$refs.reportCategoryChart) return;

      const data = chartData || this.filteredReportCategoryData;
      let chart = echarts.getInstanceByDom(this.$refs.reportCategoryChart);

      if (!chart) {
        chart = echarts.init(this.$refs.reportCategoryChart);
      }

      const option = {
        animation: false,
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
        },
        legend: {
          orient: "vertical",
          left: 10,
          top: "center",
          data: data.map(item => item.name),
        },
        series: [
          {
            name: "报告分类",
            type: "pie",
            radius: ["50%", "70%"],
            center: ["65%", "50%"],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: "center",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "18",
                fontWeight: "bold",
                formatter: (params) => {
                  return `${params.name}\n${params.value}份\n${params.percent}%`;
                }
              },
            },
            labelLine: {
              show: false,
            },
            data: data
          },
        ],
      };

      chart.setOption(option, true);
    },
    // 根据周期和筛选数据生成趋势图表数据
    generateTrendDataByPeriod(reports, period) {
      const data = {
        xAxis: [],
        reading: [],
        download: []
      };

      if (reports.length === 0) {
        // 如果没有数据，返回空数据
        return this.getEmptyTrendData(period);
      }

      // 按日期分组统计
      const groupedData = this.groupReportsByPeriod(reports, period);

      // 填充图表数据
      const periodLabels = this.getPeriodLabels(period);
      periodLabels.forEach(label => {
        data.xAxis.push(label);
        const groupData = groupedData[label] || { readCount: 0, downloadCount: 0 };
        data.reading.push(groupData.readCount);
        data.download.push(groupData.downloadCount);
      });

      return data;
    },

    // 按周期分组报告数据
    groupReportsByPeriod(reports, period) {
      const grouped = {};

      reports.forEach(report => {
        const reportDate = new Date(report.publishTime);
        let periodKey = '';

        switch (period) {
          case 'week':
            // 按周分组 (周一至周日)
            const dayOfWeek = reportDate.getDay(); // 0=周日, 1=周一, ..., 6=周六
            const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
            periodKey = weekDays[dayOfWeek];
            break;

          case 'month':
            // 按日分组
            const day = reportDate.getDate();
            periodKey = `${day}日`;
            break;

          case 'year':
            // 按月分组
            const month = reportDate.getMonth() + 1;
            periodKey = `${month}月`;
            break;
        }

        if (!grouped[periodKey]) {
          grouped[periodKey] = { readCount: 0, downloadCount: 0 };
        }

        grouped[periodKey].readCount += report.readCount;
        grouped[periodKey].downloadCount += report.downloadCount;
      });

      return grouped;
    },

    // 获取周期标签
    getPeriodLabels(period) {
      switch (period) {
        case 'week':
          return ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        case 'month':
          return Array.from({ length: 30 }, (_, i) => `${i + 1}日`);
        case 'year':
          return ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
        default:
          return [];
      }
    },

    // 获取空数据（当没有筛选结果时）
    getEmptyTrendData(period) {
      const labels = this.getPeriodLabels(period);
      return {
        xAxis: labels,
        reading: Array(labels.length).fill(0),
        download: Array(labels.length).fill(0)
      };
    },
    // 重置新建报告表单
    resetNewReportForm() {
      this.newReport = {
        title: "",
        type: "",
        author: "",
        department: "",
        publishTime: this.getCurrentDate(),
        summary: "",
        coverImage: "",
        tags: [],
      };
      this.newTag = "";
      this.formErrors = {};
      this.isSubmitting = false;
    },
    // 添加标签
    addTag() {
      if (
        this.newTag.trim() &&
        !this.newReport.tags.includes(this.newTag.trim())
      ) {
        this.newReport.tags.push(this.newTag.trim());
        this.newTag = "";
      }
    },
    // 移除标签
    removeTag(index) {
      this.newReport.tags.splice(index, 1);
    },
    // 增强表单验证方法
    validateForm() {
      const errors = {};

      if (!this.newReport.title.trim()) {
        errors.title = "报告标题不能为空";
      } else if (this.newReport.title.trim().length < 5) {
        errors.title = "报告标题至少需要5个字符";
      } else if (this.newReport.title.trim().length > 100) {
        errors.title = "报告标题不能超过100个字符";
      }

      if (!this.newReport.type) {
        errors.type = "请选择报告类型";
      }

      if (!this.newReport.author.trim()) {
        errors.author = "作者不能为空";
      } else if (this.newReport.author.trim().length > 50) {
        errors.author = "作者名称不能超过50个字符";
      }

      if (!this.newReport.publishTime) {
        errors.publishTime = "请选择发布时间";
      } else {
        // 修复日期比较逻辑，只比较日期部分，忽略时间部分
        const selectedDate = new Date(this.newReport.publishTime);
        const today = new Date();

        // 将两个日期都设置为当天的开始时间（00:00:00），以确保只比较日期部分
        const selectedDateOnly = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate());
        const todayDateOnly = new Date(today.getFullYear(), today.getMonth(), today.getDate());

        if (selectedDateOnly > todayDateOnly) {
          errors.publishTime = "发布时间不能是未来日期";
        }
      }

      if (this.newReport.summary.length > 500) {
        errors.summary = "报告摘要不能超过500个字符";
      }

      this.formErrors = errors;
      return Object.keys(errors).length === 0;
    },
    // 根据报告类型获取样式类
    getReportTypeClass(type) {
      const typeClasses = {
        月度报告: "bg-indigo-100 text-indigo-800",
        季度报告: "bg-blue-100 text-blue-800",
        半年报告: "bg-purple-100 text-purple-800",
        年度报告: "bg-red-100 text-red-800",
        专项报告: "bg-green-100 text-green-800",
        研究报告: "bg-yellow-100 text-yellow-800",
        评估报告: "bg-red-100 text-red-800",
        指导报告: "bg-blue-100 text-blue-800",
      };
      return typeClasses[type] || "bg-gray-100 text-gray-800";
    },
    // 根据报告类型获取图标样式
    getReportIconStyle(type) {
      const iconStyles = {
        月度报告: { bg: "bg-indigo-100", color: "text-indigo-600" },
        季度报告: { bg: "bg-blue-100", color: "text-blue-600" },
        半年报告: { bg: "bg-purple-100", color: "text-purple-600" },
        年度报告: { bg: "bg-red-100", color: "text-red-600" },
        专项报告: { bg: "bg-green-100", color: "text-green-600" },
        研究报告: { bg: "bg-yellow-100", color: "text-yellow-600" },
        评估报告: { bg: "bg-red-100", color: "text-red-600" },
        指导报告: { bg: "bg-blue-100", color: "text-blue-600" },
      };
      return iconStyles[type] || { bg: "bg-gray-100", color: "text-gray-600" };
    },
    // 保存报告数据到本地存储
    saveReportData() {
      try {
        localStorage.setItem("reportList", JSON.stringify(this.reportList));
        this.updateReportStatistics();
      } catch (error) {
      }
    },
    // 从本地存储加载报告数据
    loadReportData() {
      try {
        const savedData = localStorage.getItem("reportList");
        if (savedData) {
          this.reportList = JSON.parse(savedData);
          this.updateReportStatistics();
        }
      } catch (error) {
      }
    },
    // 更新报告统计信息
    updateReportStatistics() {
      this.totalReports = this.reportList.length;

      // 更新本月新增统计
      const currentMonth = new Date().getMonth() + 1;
      const currentYear = new Date().getFullYear();
      const monthlyNew = this.reportList.filter((report) => {
        const reportDate = new Date(report.publishTime);
        return (
          reportDate.getMonth() + 1 === currentMonth &&
          reportDate.getFullYear() === currentYear
        );
      }).length;

      // 更新待阅报告统计
      const unreadCount = this.reportList.filter(
        (report) => !report.isRead
      ).length;


    },
    // 检查报告是否已存在（防止重复创建）
    isReportExists(title, author, publishTime) {
      return this.reportList.some(
        (report) =>
          report.title === title &&
          report.author === author &&
          report.publishTime === publishTime
      );
    },
    // 提交新建报告方法
    async submitNewReport() {
      if (!this.validateForm()) {
        return;
      }

      const authorDisplay = this.newReport.department
        ? `${this.newReport.department} - ${this.newReport.author}`
        : this.newReport.author;

      if (this.isReportExists(this.newReport.title, authorDisplay, this.newReport.publishTime)) {
        ElMessageBox.alert("相同标题、作者和发布时间的报告已存在，请勿重复创建！", "警告", {
          confirmButtonText: "确定",
          type: "warning",
        });
        return;
      }

      this.isSubmitting = true;
      try {
        await new Promise((resolve) => setTimeout(resolve, 1500));

        const iconStyle = this.getReportIconStyle(this.newReport.type);
        const newReportItem = {
          id: Date.now(),
          title: this.newReport.title,
          author: authorDisplay,
          type: this.newReport.type,
          typeClass: this.getReportTypeClass(this.newReport.type),
          icon: "fas fa-file-alt",
          iconBg: iconStyle.bg,
          iconColor: iconStyle.color,
          publishTime: this.newReport.publishTime,
          isRead: false,
          readCount: 0,
          downloadCount: 0,
          summary: this.newReport.summary,
          tags: [...this.newReport.tags],
          createdAt: new Date().toISOString(),
        };

        this.reportList.unshift(newReportItem);
        this.saveReportData();

        // 新增：更新图表
        this.updateCharts();

        ElMessage.success("报告创建成功！");

        this.$nextTick(() => {
          this.showNewReportModal = false;
          this.resetNewReportForm();
        });
      } catch (error) {
        ElMessageBox.alert("报告创建失败，请重试");
      } finally {
        this.isSubmitting = false;
      }
    },
    // 关闭新建报告弹窗
    closeNewReportModal() {
      this.showNewReportModal = false;
      // 立即重置表单，不需要延迟
      this.resetNewReportForm();
    },
    // 确认删除报告
    confirmDeleteReport(report) {
      this.reportToDelete = report;
      this.showDeleteConfirmModal = true;
    },

    // 关闭删除确认弹窗
    closeDeleteConfirmModal() {
      this.showDeleteConfirmModal = false;
      this.reportToDelete = null;
      this.isDeleting = false;
    },

    // 执行删除报告
    async deleteReport() {
      if (!this.reportToDelete) return;

      this.isDeleting = true;

      try {
        await new Promise((resolve) => setTimeout(resolve, 1000));

        const index = this.reportList.findIndex(
          (report) => report.id === this.reportToDelete.id
        );
        if (index !== -1) {
          this.reportList.splice(index, 1);
          this.saveReportData();

          // 新增：更新图表
          this.updateCharts();

          ElMessage.success("报告删除成功！");
        }

        this.closeDeleteConfirmModal();
      } catch (error) {
        ElMessage.error("报告删除失败，请重试");
      } finally {
        this.isDeleting = false;
      }
    },
    toggleMenu(index) {
      this.mainMenus[index].expanded = !this.mainMenus[index].expanded;
      // 如果展开了菜单，则将其他菜单收起
      if (this.mainMenus[index].expanded) {
        this.mainMenus.forEach((menu, i) => {
          if (i !== index) {
            menu.expanded = false;
          }
        });
      }
    },
    selectSubmenu(menuIndex, submenuIndex) {
      // 重置所有菜单的激活状态
      this.mainMenus.forEach((menu) => {
        menu.active = false;
        menu.subMenus.forEach((submenu) => {
          submenu.active = false;
        });
      });
      // 设置当前选中的菜单和子菜单为激活状态
      this.mainMenus[menuIndex].active = true;
      this.mainMenus[menuIndex].subMenus[submenuIndex].active = true;
    },
    updateCurrentTime() {
      const now = new Date();
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      this.currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    handleResize() {
      // 获取所有图表实例并调整大小
      const chartRefs = [
        this.$refs.reportCategoryChart,
        this.$refs.reportReadingTrendChart,
      ];
      chartRefs.forEach((ref) => {
        if (ref) {
          const chart = echarts.getInstanceByDom(ref);
          if (chart) {
            chart.resize();
          }
        }
      });
    },
    changePeriod(period) {
      this.currentPeriod = period;
      this.updateReportReadingTrendChart();
    },
    // 更新报告阅读趋势图表
    updateReportReadingTrendChart() {
      if (!this.$refs.reportReadingTrendChart) return;

      let chart = echarts.getInstanceByDom(this.$refs.reportReadingTrendChart);
      if (!chart) {
        chart = echarts.init(this.$refs.reportReadingTrendChart);
      }

      // 使用筛选后的数据
      const trendData = this.filteredTrendData;

      // 根据数据长度调整柱状图宽度
      const barWidth =
        this.currentPeriod === "week"
          ? "30%"
          : this.currentPeriod === "month"
            ? "10%"
            : "60%";

      // 根据数据长度调整X轴标签间隔
      const interval =
        this.currentPeriod === "week"
          ? 0
          : this.currentPeriod === "month"
            ? 4
            : 0;

      const option = {
        animation: false,
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: (params) => {
            let result = `${params[0].axisValue}<br/>`;
            params.forEach(param => {
              result += `${param.seriesName}: ${param.value}<br/>`;
            });
            return result;
          }
        },
        legend: {
          data: ["阅读量", "下载量"],
          top: 10,
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          top: "15%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: trendData.xAxis,
            axisLine: {
              lineStyle: {
                color: "#e2e8f0",
              },
            },
            axisLabel: {
              color: "#718096",
              fontSize: 10,
              interval: interval,
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "数量",
            axisLabel: {
              formatter: "{value}",
              color: "#718096",
            },
            axisLine: {
              show: false,
            },
            splitLine: {
              lineStyle: {
                color: "#e2e8f0",
              },
            },
          },
        ],
        series: [
          {
            name: "阅读量",
            type: "bar",
            barWidth: barWidth,
            itemStyle: {
              color: "#4299e1",
            },
            data: trendData.reading,
          },
          {
            name: "下载量",
            type: "bar",
            barWidth: barWidth,
            itemStyle: {
              color: "#48bb78",
            },
            data: trendData.download,
          }
        ],
      };

      chart.setOption(option, true);
    },
    // 查看报告详情
    viewReport(report) {

      this.reportDetail = { ...report };
      this.showReportDetailModal = true;
      // 标记为已读（如果未读）
      if (!report.isRead) {
        this.markAsRead(report);
      }
    },
    // 关闭报告详情弹窗
    closeReportDetail() {
      this.showReportDetailModal = false;
      this.reportDetail = null;
      this.downloadProgress = 0;
      this.isDownloading = false;
    },
    // 下载报告
    async downloadReport(report) {

      this.isDownloading = true;
      this.downloadProgress = 0;
      try {
        // 模拟下载过程
        for (let i = 0; i <= 100; i += 10) {
          await new Promise((resolve) => setTimeout(resolve, 200));
          this.downloadProgress = i;
        }
        // 更新下载计数
        const reportIndex = this.reportList.findIndex(
          (r) => r.id === report.id
        );
        if (reportIndex !== -1) {
          this.reportList[reportIndex].downloadCount += 1;
          this.saveReportData();
        }
        // 生成下载文件
        this.generateDownloadFile(report);
        // 显示成功消息
        this.showNotification(
          "下载成功",
          `报告"${report.title}"已开始下载`,
          "success"
        );
      } catch (error) {
        this.showNotification("下载失败", "请检查网络连接后重试", "error");
      } finally {
        this.isDownloading = false;
        this.downloadProgress = 0;
      }
    },
    // 从详情页下载
    downloadReportFromDetail(report) {
      this.downloadReport(report);
    },
    // 生成下载文件
    generateDownloadFile(report) {
      // 创建虚拟文件内容
      const content = `
            报告标题: ${report.title}
            作者: ${report.author}
            类型: ${report.type}
            发布时间: ${report.publishTime}

            ================================
            报告内容摘要
            ================================

            这是一份关于${report.type}的详细分析报告。
            报告包含了详细的数据分析、趋势预测和改进建议。

            主要内容包括：
            - 当前行业现状分析
            - 关键指标数据统计
            - 风险评估与预测
            - 改进措施建议
            - 未来发展趋势

            下载时间: ${new Date().toLocaleString()}
        `;
      // 创建Blob对象并下载
      const blob = new Blob([content], { type: "text/plain;charset=utf-8" });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = `${report.title}.txt`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    },

    // 显示热门报告详情
    showHotReportDetail(report) {
      this.hotReportDetail = report;
      this.showHotReportDetailModal = true;
    },

    // 关闭热门报告详情弹窗
    closeHotReportDetailModal() {
      this.showHotReportDetailModal = false;
      this.hotReportDetail = null;
    },

    // 下载热门报告
    downloadHotReport() {
      if (!this.hotReportDetail) return;

      // 模拟下载
      const content = `
            ================================
            钢铁企业安全生产智能监管平台
            ================================

            报告标题: ${this.hotReportDetail.title}
            报告类型: ${this.hotReportDetail.type}
            发布时间: ${this.hotReportDetail.publishTime}

            ================================
            报告内容摘要
            ================================

            这是一份关于${this.hotReportDetail.type}的详细分析报告。
            报告包含了详细的数据分析、趋势预测和改进建议。

            主要内容包括：
            - 当前行业现状分析
            - 关键指标数据统计
            - 风险评估与预测
            - 改进措施建议
            - 未来发展趋势

            下载时间: ${new Date().toLocaleString()}
        `;
      // 创建Blob对象并下载
      const blob = new Blob([content], { type: "text/plain;charset=utf-8" });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = `${this.hotReportDetail.title}.txt`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);

      // 更新下载计数
      this.hotReportDetail.downloadCount += 1;

      // 显示成功消息
      this.$message({
        message: '报告下载成功',
        type: 'success'
      });
    },

    // 标记为已读
    markAsRead(report) {
      const reportIndex = this.reportList.findIndex((r) => r.id === report.id);
      if (reportIndex !== -1 && !this.reportList[reportIndex].isRead) {
        this.reportList[reportIndex].isRead = true;
        this.reportList[reportIndex].readCount += 1;
        this.saveReportData();

        // 如果当前在详情页，也更新详情数据
        if (this.reportDetail && this.reportDetail.id === report.id) {
          this.reportDetail.isRead = true;
          this.reportDetail.readCount += 1;
        }

      }
    },

    // 显示通知
    showNotification(title, message, type = "info") {
      const messageType =
        type === "error"
          ? "error"
          : type === "success"
            ? "success"
            : type === "warning"
              ? "warning"
              : "info";

      ElMessage({
        message: `${title}: ${message}`,
        type: messageType,
        duration: 3000,
      });
    },
    initReportCategoryChart() {
      this.updateReportCategoryChart();
      if (!this.$refs.reportCategoryChart) return;
      const chart = echarts.init(this.$refs.reportCategoryChart);
      const option = {
        animation: false,
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
        },
        legend: {
          orient: "vertical",
          left: 10,
          top: "center",
          data: [
            "月度报告",
            "季度报告",
            "半年报告",
            "年度报告",
            "专项报告",
            "研究报告",
            "评估报告",
            "指导报告",
          ],
        },
        series: [
          {
            name: "报告分类",
            type: "pie",
            radius: ["50%", "70%"],
            center: ["65%", "50%"],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: "center",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "18",
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: false,
            },
            data: [
              { value: 24, name: "月度报告", itemStyle: { color: "#4299e1" } },
              { value: 8, name: "季度报告", itemStyle: { color: "#48bb78" } },
              { value: 4, name: "半年报告", itemStyle: { color: "#9f7aea" } },
              { value: 2, name: "年度报告", itemStyle: { color: "#f56565" } },
              { value: 38, name: "专项报告", itemStyle: { color: "#38b2ac" } },
              { value: 28, name: "研究报告", itemStyle: { color: "#ecc94b" } },
              { value: 18, name: "评估报告", itemStyle: { color: "#ed8936" } },
              { value: 6, name: "指导报告", itemStyle: { color: "#667eea" } },
            ],
          },
        ],
      };
      chart.setOption(option);
    },
    // 初始化报告阅读趋势图表
    initReportReadingTrendChart() {
      this.updateReportReadingTrendChart();
    },
    // 更新所有图表
    updateCharts() {
      this.updateReportCategoryChart();
      this.updateReportReadingTrendChart();
    },

  },
};
</script>
<style scoped>
/* 隐藏input number的箭头 */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

input[type="number"] {
  -moz-appearance: textfield;
}

/* 文本截断 */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 自定义颜色类 */
.bg-blue-100 {
  background-color: #ebf8ff;
}

.bg-red-100 {
  background-color: #fed7d7;
}

.bg-green-100 {
  background-color: #c6f6d5;
}

.bg-yellow-100 {
  background-color: #fefcbf;
}

.bg-purple-100 {
  background-color: #e9d8fd;
}

.bg-orange-100 {
  background-color: #feebc8;
}

.bg-teal-100 {
  background-color: #b2f5ea;
}

.bg-indigo-100 {
  background-color: #e5edff;
}

.text-blue-600 {
  color: #3182ce;
}

.text-red-600 {
  color: #e53e3e;
}

.text-green-600 {
  color: #38a169;
}

.text-yellow-600 {
  color: #d69e2e;
}

.text-purple-600 {
  color: #805ad5;
}

.text-orange-600 {
  color: #dd6b20;
}

.text-teal-600 {
  color: #319795;
}

.text-indigo-600 {
  color: #5a67d8;
}

.text-blue-800 {
  color: #2c5282;
}

.text-red-800 {
  color: #9b2c2c;
}

.text-green-800 {
  color: #276749;
}

.text-yellow-800 {
  color: #975a16;
}

.text-purple-800 {
  color: #553c9a;
}

.text-indigo-800 {
  color: #434190;
}
</style>
